package bma.common.mq.outer.service;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import base.Queue;
import bma.common.mq.outer.po.Consumer;
import bma.common.mq.outer.po.SEND_RESULT;
import bma.common.mq.outer.thrift.TMessageInfo;
//TODO

/**
 * 接收器和调度器实现类
 * @author Administrator
 *
 */
public class ReceiveServiceImpl {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ReceiveServiceImpl.class);
	
	private IRemoveDuplicateService removeDuplicateService;
	
	private RegisterServiceImpl registerService;

	public void setRemoveDuplicateService(
			IRemoveDuplicateService removeDuplicateService) {
		this.removeDuplicateService = removeDuplicateService;
	}


	public void setRegisterService(RegisterServiceImpl registerService) {
		this.registerService = registerService;
	}


	public SEND_RESULT receiveMessage(TMessageInfo msgInfo){
		if(msgInfo == null)
			return SEND_RESULT.NULL;
		
		SEND_RESULT result = checkMessage(msgInfo);
		if(!result.equal(SEND_RESULT.SUCCESS)){
			return result;
		}
		
		if(removeDuplicateService.handle(msgInfo)){// 排重
			return SEND_RESULT.DUPLICATE;
		}
		
		if(sendMessage(msgInfo)){
			return SEND_RESULT.SUCCESS;
		}
		
		return SEND_RESULT.FAIL;
	}
	
	private SEND_RESULT checkMessage(TMessageInfo msgInfo){
		SEND_RESULT result = SEND_RESULT.VALID;
		if(!registerService.hasMessageBase(msgInfo.getCategory())) // 消息元不包含此类别
			result.setMsg("不允许发送此类消息！");
		else if(!registerService.isUidExist(msgInfo.getUid())){ // 是否存在该用户注册信息
			result.setMsg("此用户不允许发送消息！");
		}
		else if(msgInfo.getContent().trim().isEmpty()){ // 消息内容是否为空
			result.setMsg("消息内容不能为空！");
		}else{
			result = SEND_RESULT.SUCCESS;
		}
		return result;
	}
	
	
	private boolean sendMessage(TMessageInfo msg){
		String category = msg.getCategory();
		List<Consumer> consumers = registerService.getConsumers(category);
		Map<Integer, Queue> queues = registerService.getQueues();
		long receiveTime = Calendar.getInstance().getTime().getTime();
		for(Consumer consumer : consumers){
			Queue queue = queues.get(consumer.getId());
			// TODO 发送消息到队列 queueServer.receive(category,receiveTime,msg.getContent(),queue);
		}
		return true;
	}
}
